import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { Observable } from 'rxjs/Observable';

import { NvModalService } from 'ng-valley';
import { map } from 'rxjs/operators/map';
export interface CanComponentDeactivate {
  canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
  ifCompose: boolean;
  saveP: () => Promise<{ ifLeave: boolean }>;
}

@Injectable({
  providedIn: 'root'
})
export class CanDeactivateGuardService implements CanDeactivate<CanComponentDeactivate> {
  constructor(private nvSv: NvModalService) { }
  canDeactivate(component: CanComponentDeactivate) {
    if (typeof component.canDeactivate === 'function') {
      return component.canDeactivate();
    } else {
      if (component.ifCompose) {
        if (component.saveP) {
          let ifLeave = false;
          const option = {
            nvContent: '是否要保存修改？',
            nvWrapClassName: 'confirmWrap',
            nvIconType: '',
            nvMaskClosable: true,
            nvOnOk: () => {
              return component.saveP();
            },
            nvOnCancel: () => {
              ifLeave = true;
              return { ifLeave };
            }
          };
          const afterClose$ = this.nvSv.confirm(option).afterClose;
          return afterClose$.pipe(
            map(value => {
              return value.ifLeave;
            })
          );
        } else {
          return true;
        }

      } else {
        return true;
      }
    }
  }
}
